<template>
  <div class="display-container" @click="onBackgroundClick">
    <header class="display-header">
      <div class="logo-text">江苏中烟工业有限责任公司</div>
      <h1 class="display-title">竞聘人员得分</h1>
      <div class="refresh-info">
        <p>点击屏幕任意位置刷新数据</p>
        <p class="last-update">最后更新：<span id="lastUpdate">{{ lastUpdateTime }}</span></p>
      </div>
    </header>
    <main class="display-content" style="display:flex;align-items:center;justify-content:center;">
      <div v-if="!contestant" class="no-data">
        <h2>暂无激活选手</h2>
        <p>请在管理界面激活选手</p>
      </div>
      <div v-else class="current-contestant-display" :class="{ 
        'no-score': totalScores < totalJudges, 
        'has-score': totalScores >= totalJudges,
        'score-excellent': totalScores >= totalJudges && adjustedAverage >= 90,
        'score-good': totalScores >= totalJudges && adjustedAverage >= 80 && adjustedAverage < 90,
        'score-average': totalScores >= totalJudges && adjustedAverage >= 70 && adjustedAverage < 80,
        'score-poor': totalScores >= totalJudges && adjustedAverage < 70
      }" style="max-width:640px; width:100%;">
        <div class="contestant-name">{{ contestant.number }} - {{ contestant.name }}</div>
        <div class="score-container">
          <div v-if="totalScores < totalJudges" class="contestant-score waiting" key="waiting">待评分</div>
          <div v-else class="contestant-score score-flip" :key="adjustedAverage">{{ adjustedAverage.toFixed(1) }}</div>
        </div>
        <div v-if="totalScores < totalJudges" class="contestant-rank">等待评委打分 ({{ totalScores }}/{{ totalJudges }})</div>
        <div v-else class="contestant-rank">
          去掉最高分和最低分后的平均分
          <!-- <div v-if="adjustedAverage >= 90" class="score-level excellent">优秀</div>
          <div v-else-if="adjustedAverage >= 80" class="score-level good">良好</div>
          <div v-else-if="adjustedAverage >= 70" class="score-level average">中等</div>
          <div v-else class="score-level poor">待提升</div> -->
        </div>
        <div v-if="totalScores >= totalJudges" class="score-count">有效评分数量：{{ effectiveCount }}（总评分：{{ totalScores }}）</div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useScoringStore } from '@/stores/scoring'
import { contestantApi, judgeApi } from '@/api'
import '@/assets/display.css'

const scoringStore = useScoringStore()

type ActiveAdjusted = { contestant: { id: number; number: string; name: string } | null; adjusted_average: number; total_scores: number }

const contestant = ref<ActiveAdjusted['contestant']>(null)
const adjustedAverage = ref(0)
const totalScores = ref(0)
const effectiveCount = ref(0)
const totalJudges = ref(0)
const lastUpdateTime = ref('')

async function loadCurrent() {
  await scoringStore.initialize()
  
  // 获取评委总数
  const judgesData = await judgeApi.getCount()
  totalJudges.value = judgesData.total_judges
  
  const data = await contestantApi.getActiveAdjustedAverage()
  
  // 检查是否有激活的选手
  if (data.contestant) {
    contestant.value = data.contestant
    adjustedAverage.value = data.adjusted_average || 0
    totalScores.value = data.total_scores || 0
    effectiveCount.value = data.total_scores || 0
  } else {
    // 没有激活选手时，清空显示
    contestant.value = null
    adjustedAverage.value = 0
    totalScores.value = 0
    effectiveCount.value = 0
  }
  
  const now = new Date()
  lastUpdateTime.value = now.toLocaleString('zh-CN')
}

async function refreshData() {
  showRefreshing()
  try {
    await loadCurrent()
    showRefreshSuccess()
  } catch (e) {
    showError('刷新失败，请重试')
  }
}

function onBackgroundClick(e: MouseEvent) {
  const t = e.target as HTMLElement
  if (['BUTTON', 'INPUT', 'SELECT'].includes(t.tagName)) return
  refreshData()
}

function showRefreshing() {
  const tip = document.createElement('div')
  tip.id = 'refreshTip'
  tip.className = 'refresh-tip'
  tip.textContent = '正在刷新数据...'
  tip.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,.8);color:#fff;padding:20px 40px;border-radius:10px;font-size:1.2rem;z-index:1000;'
  document.body.appendChild(tip)
}
function showRefreshSuccess() {
  const tip = document.getElementById('refreshTip')
  tip && tip.remove()
  showSuccessTip('数据已更新')
}
function showSuccessTip(message: string) {
  const tip = document.createElement('div')
  tip.className = 'success-tip'
  tip.textContent = message
  tip.style.cssText = 'position:fixed;top:20px;right:20px;background:#28a745;color:#fff;padding:10px 20px;border-radius:5px;font-size:1rem;z-index:1000;animation:slideIn .3s ease-out;'
  document.body.appendChild(tip)
  setTimeout(() => tip.remove(), 2000)
}
function showError(message: string) {
  const tip = document.createElement('div')
  tip.className = 'error-tip'
  tip.textContent = message
  tip.style.cssText = 'position:fixed;top:20px;right:20px;background:#dc3545;color:#fff;padding:10px 20px;border-radius:5px;font-size:1rem;z-index:1000;animation:slideIn .3s ease-out;'
  document.body.appendChild(tip)
  setTimeout(() => tip.remove(), 3000)
}

onMounted(async () => {
  await loadCurrent()
  // 每3秒检查一次当前选手状态
  // setInterval(loadCurrent, 3000)
  document.addEventListener('keydown', async (e) => {
    if (e.key === 'F5' || e.key === 'r' || e.key === 'R') {
      e.preventDefault()
      await refreshData()
    }
  })
})
</script>
